package com.kakarote.hrm.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.BigExcelWriter;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.excel.EasyExcel;
import com.kakarote.common.log.entity.OperationLog;
import com.kakarote.common.log.enums.BehaviorEnum;
import com.kakarote.core.common.MultipartFileUtil;
import com.kakarote.core.common.Result;
import com.kakarote.core.common.cache.AdminCacheKey;
import com.kakarote.core.common.cache.HrmCacheKey;
import com.kakarote.core.common.enums.FieldEnum;
import com.kakarote.core.common.enums.SystemCodeEnum;
import com.kakarote.core.entity.BasePage;
import com.kakarote.core.entity.UploadEntity;
import com.kakarote.core.exception.CrmException;
import com.kakarote.core.feign.admin.service.AdminFileService;
import com.kakarote.core.redis.Redis;
import com.kakarote.core.servlet.BaseServiceImpl;
import com.kakarote.core.utils.ExcelParseUtil;
import com.kakarote.hrm.constant.RecruitPositionConstant;
import com.kakarote.hrm.entity.BO.QueryRecruitPositionPageListBO;
import com.kakarote.hrm.entity.PO.HrmRecruitPlan;
import com.kakarote.hrm.entity.PO.HrmRecruitPosition;
import com.kakarote.hrm.entity.VO.RecruitPositionExportVO;
import com.kakarote.hrm.entity.VO.RecruitPositionVO;
import com.kakarote.hrm.mapper.HrmRecruitPlanMapper;
import com.kakarote.hrm.mapper.HrmRecruitPositionMapper;
import com.kakarote.hrm.service.IHrmRecruitPositionService;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 招聘岗位 服务实现类
 * </p>
 *
 * @author system
 * @since 2024-01-01
 */
@Service
public class HrmRecruitPositionServiceImpl extends BaseServiceImpl<HrmRecruitPositionMapper, HrmRecruitPosition> implements IHrmRecruitPositionService {

    @Autowired
    private HrmRecruitPositionMapper recruitPositionMapper;

    @Autowired
    private HrmRecruitPlanMapper recruitPlanMapper;

    @Autowired
    private HrmRecruitPlanServiceImpl recruitPlanService;

    @Autowired
    private Redis redis;

    @Resource
    private AdminFileService adminFileService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OperationLog addRecruitPosition(HrmRecruitPosition recruitPosition) {
        // 查找计划
        HrmRecruitPlan recruitPlan = recruitPlanMapper.selectById(recruitPosition.getPlanId());
        if (recruitPlan == null) {
            throw new CrmException(SystemCodeEnum.SYSTEM_ERROR.getCode(), "招聘计划不存在");
        }
        // 生成岗位编码
        if (StrUtil.isEmpty(recruitPosition.getPositionCode())) {
            recruitPosition.setPositionCode(generatePositionCode(recruitPlan.getPlanCode()));
        }
        save(recruitPosition);

        OperationLog operationLog = new OperationLog();
        operationLog.setOperationObject(recruitPosition.getPositionId(), recruitPosition.getPositionName());
        String detail = String.format("岗位名称：%s，岗位编码：%s，招聘数量：%d，招聘单位：%s",
                recruitPosition.getPositionName(),
                StrUtil.isNotEmpty(recruitPosition.getPositionCode()) ? recruitPosition.getPositionCode() : "无",
                recruitPosition.getPositionNum() != null ? recruitPosition.getPositionNum() : 0,
                StrUtil.isNotEmpty(recruitPosition.getPositionUnit()) ? recruitPosition.getPositionUnit() : "无");
        operationLog.setOperationInfo(detail);
        operationLog.setBehavior(BehaviorEnum.SAVE);
        return operationLog;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OperationLog setRecruitPosition(HrmRecruitPosition recruitPosition) {
        HrmRecruitPosition oldPosition = getById(recruitPosition.getPositionId());
        if (oldPosition == null) {
            throw new CrmException(SystemCodeEnum.SYSTEM_ERROR.getCode(), "招聘岗位不存在");
        }

        // 记录变更内容
        StringBuilder detail = new StringBuilder();
        if (!Objects.equals(oldPosition.getPositionName(), recruitPosition.getPositionName())) {
            detail.append(String.format("岗位名称：%s → %s；", oldPosition.getPositionName(), recruitPosition.getPositionName()));
        }
        if (!Objects.equals(oldPosition.getPositionCode(), recruitPosition.getPositionCode())) {
            detail.append(String.format("岗位编码：%s → %s；",
                    StrUtil.isNotEmpty(oldPosition.getPositionCode()) ? oldPosition.getPositionCode() : "无",
                    StrUtil.isNotEmpty(recruitPosition.getPositionCode()) ? recruitPosition.getPositionCode() : "无"));
        }
        if (!Objects.equals(oldPosition.getPositionNum(), recruitPosition.getPositionNum())) {
            detail.append(String.format("招聘数量：%d → %d；",
                    oldPosition.getPositionNum() != null ? oldPosition.getPositionNum() : 0,
                    recruitPosition.getPositionNum() != null ? recruitPosition.getPositionNum() : 0));
        }
        if (!Objects.equals(oldPosition.getPositionReason(), recruitPosition.getPositionReason())) {
            detail.append(String.format("招聘原因：%s → %s；",
                    StrUtil.isNotEmpty(oldPosition.getPositionReason()) ? oldPosition.getPositionReason() : "无",
                    StrUtil.isNotEmpty(recruitPosition.getPositionReason()) ? recruitPosition.getPositionReason() : "无"));
        }
        if (!Objects.equals(oldPosition.getPositionCondition(), recruitPosition.getPositionCondition())) {
            detail.append(String.format("招聘条件：%s → %s；",
                    StrUtil.isNotEmpty(oldPosition.getPositionCondition()) ? oldPosition.getPositionCondition() : "无",
                    StrUtil.isNotEmpty(recruitPosition.getPositionCondition()) ? recruitPosition.getPositionCondition() : "无"));
        }
        if (!Objects.equals(oldPosition.getPositionType(), recruitPosition.getPositionType())) {
            detail.append(String.format("岗位类别：%s → %s；",
                    RecruitPositionConstant.PositionTypeEnum.getNameByType(oldPosition.getPositionType()),
                    RecruitPositionConstant.PositionTypeEnum.getNameByType(recruitPosition.getPositionType())));
        }
        if (!Objects.equals(oldPosition.getPositionChannel(), recruitPosition.getPositionChannel())) {
            detail.append(String.format("招聘渠道：%s → %s；",
                    RecruitPositionConstant.PositionChannelEnum.getNameByChannel(oldPosition.getPositionChannel()),
                    RecruitPositionConstant.PositionChannelEnum.getNameByChannel(recruitPosition.getPositionChannel())));
        }
        if (!Objects.equals(oldPosition.getPositionUnit(), recruitPosition.getPositionUnit())) {
            detail.append(String.format("招聘单位：%s → %s；",
                    StrUtil.isNotEmpty(oldPosition.getPositionUnit()) ? oldPosition.getPositionUnit() : "无",
                    StrUtil.isNotEmpty(recruitPosition.getPositionUnit()) ? recruitPosition.getPositionUnit() : "无"));
        }

        updateById(recruitPosition);
        OperationLog operationLog = new OperationLog();
        operationLog.setOperationObject(recruitPosition.getPositionId(), recruitPosition.getPositionName());
        operationLog.setOperationInfo(detail.toString());
        operationLog.setBehavior(BehaviorEnum.UPDATE);
        return operationLog;
    }

    @Override
    public RecruitPositionVO queryById(Long positionId) {
        return recruitPositionMapper.queryById(positionId);
    }

    @Override
    public BasePage<RecruitPositionVO> queryRecruitPositionPageList(QueryRecruitPositionPageListBO queryRecruitPositionPageListBO) {
        BasePage<RecruitPositionVO> page = queryRecruitPositionPageListBO.parse();
        return recruitPositionMapper.queryRecruitPositionPageList(page, queryRecruitPositionPageListBO);
    }

    @Override
    public List<RecruitPositionVO> queryByPlanId(Long planId) {
        return recruitPositionMapper.queryByPlanId(planId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OperationLog deleteRecruitPosition(Long positionId) {
        HrmRecruitPosition position = getById(positionId);
        if (position == null) {
            throw new CrmException(SystemCodeEnum.SYSTEM_ERROR.getCode(), "招聘岗位不存在");
        }

        removeById(positionId);
        OperationLog operationLog = new OperationLog();
        operationLog.setOperationObject(positionId, position.getPositionName());
        operationLog.setOperationInfo(String.format("删除岗位：%s", position.getPositionName()));
        operationLog.setBehavior(BehaviorEnum.DELETE);
        return operationLog;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OperationLog batchDeleteRecruitPosition(List<Long> positionIds) {
        if (positionIds == null || positionIds.isEmpty()) {
            throw new CrmException(SystemCodeEnum.SYSTEM_ERROR.getCode(), "请选择要删除的岗位");
        }

        List<HrmRecruitPosition> positions = listByIds(positionIds);
        if (positions.isEmpty()) {
            throw new CrmException(SystemCodeEnum.SYSTEM_ERROR.getCode(), "选择的岗位不存在");
        }

        removeByIds(positionIds);
        OperationLog operationLog = new OperationLog();
        operationLog.setOperationObject(positionIds.toString(), "批量删除岗位");
        StringBuilder detail = new StringBuilder("删除岗位：");
        for (HrmRecruitPosition position : positions) {
            detail.append(position.getPositionName()).append("、");
        }
        if (detail.length() > 0) {
            detail.setLength(detail.length() - 1);
        }
        operationLog.setOperationInfo(detail.toString());
        operationLog.setBehavior(BehaviorEnum.DELETE);
        return operationLog;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OperationLog deleteByPlanId(Long planId) {
        Map<String, Object> params = new HashMap<>();
        params.put("plan_id", planId);
        List<HrmRecruitPosition> positions = listByMap(params);

        OperationLog operationLog = new OperationLog();
        operationLog.setOperationObject(planId, "删除计划下所有岗位");
        operationLog.setOperationInfo(String.format("删除计划下所有岗位，共%d个", positions.size()));
        operationLog.setBehavior(BehaviorEnum.DELETE);
        return operationLog;
    }


    /**
     * 生成岗位编号
     *
     * @return 计划编号
     */
    private String generatePositionCode(String planCode) {
        StringBuffer sb = new StringBuffer();
        String key = HrmCacheKey.HRM_RECRUIT_PLAN + planCode;
        sb.append("P");
        sb.append(planCode);
        sb.append("_");
        sb.append(String.format("%05d", redis.incr(key)));
        return sb.toString();
    }

    @Override
    public void exportRecruitPosition(HttpServletResponse response, QueryRecruitPositionPageListBO queryRecruitPositionPageListBO) throws IOException {
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = "招聘岗位_" + DateUtil.format(new Date(), "yyyyMMddHHmmss") + ".xlsx";
        response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));

        // 直接查询所有符合条件的数据（不分页）
        List<RecruitPositionVO> dataList = recruitPositionMapper.queryAllRecruitPositionList(queryRecruitPositionPageListBO);

        // 转换为导出VO
        List<RecruitPositionExportVO> exportList = new ArrayList<>();
        for (RecruitPositionVO vo : dataList) {
            RecruitPositionExportVO exportVO = new RecruitPositionExportVO();
            exportVO.setPlanName(vo.getPlanName());
            exportVO.setPositionCode(vo.getPositionCode());
            exportVO.setPositionName(vo.getPositionName());
            exportVO.setPositionReason(vo.getPositionReason());
            exportVO.setPositionNum(vo.getPositionNum());
            exportVO.setPositionCondition(vo.getPositionCondition());
            exportVO.setPositionTypeName(RecruitPositionConstant.PositionTypeEnum.getNameByType(vo.getPositionType()));
            exportVO.setPositionChannelName(RecruitPositionConstant.PositionChannelEnum.getNameByChannel(vo.getPositionChannel()));
            exportVO.setPositionUnit(vo.getPositionUnit());
            exportVO.setCreateTime(vo.getCreateTime());
            exportVO.setCreateRealName(vo.getCreateRealName());
            exportList.add(exportVO);
        }

        // 使用EasyExcel导出
        EasyExcel.write(response.getOutputStream(), RecruitPositionExportVO.class)
                .sheet("招聘岗位")
                .doWrite(exportList);
    }

    @Override
    public void downloadExcel(HttpServletResponse response) {
        List<JSONObject> list = queryField();
        ExcelParseUtil.importExcel(new ExcelParseUtil.ExcelParseService() {
            @Override
            public String getExcelName() {
                return "岗位";
            }

            @Override
            public String getMergeContent(String module) {
                return "注意事项：\n" +
                        "1、表头标“*”的红色字体为必填项\n" +
                        "2、导入只新增不修改\n" +
                        "3、计划编号和计划名称必须已存在\n" +
                        "4、岗位类别只允许填写：管理岗，专技岗，工勤岗，或者不填\n" +
                        "5、招聘渠道只允许填写：校招，社招，或者不填\n";
            }
        }, list, response, "user");
    }

    private List<JSONObject> queryField() {
        List<JSONObject> list = new ArrayList<>();
        list.add(queryField("planName", FieldEnum.TEXT.getFormType(), FieldEnum.TEXT.getType(), "计划名称", 1));
        list.add(queryField("planCode", FieldEnum.TEXT.getFormType(), FieldEnum.TEXT.getType(), "计划编号", 1));
        list.add(queryField("positionName", FieldEnum.TEXT.getFormType(), FieldEnum.TEXT.getType(), "招聘岗位", 1));
        list.add(queryField("positionReason", FieldEnum.TEXT.getFormType(), FieldEnum.TEXT.getType(), "招聘原因", 0));
        list.add(queryField("positionNum", FieldEnum.NUMBER.getFormType(), FieldEnum.NUMBER.getType(), "招聘数量", 1));
        list.add(queryField("positionCondition", FieldEnum.TEXT.getFormType(), FieldEnum.TEXT.getType(), "招聘条件", 0));
        list.add(queryField("positionType", FieldEnum.NUMBER.getFormType(), FieldEnum.NUMBER.getType(), "岗位类别[管理岗、专技岗、工勤岗]", 0));
        list.add(queryField("positionChannel", FieldEnum.NUMBER.getFormType(), FieldEnum.NUMBER.getType(), "招聘渠道[校招、社招]", 0));
        list.add(queryField("positionUnit", FieldEnum.TEXT.getFormType(), FieldEnum.TEXT.getType(), "招聘单位", 0));
        return list;
    }

    private JSONObject queryField(String fieldName, String formType, Integer type, String name, Integer isNull) {
        JSONObject json = new JSONObject();
        json.fluentPut("fieldName", fieldName)
                .fluentPut("formType", formType)
                .fluentPut("type", type)
                .fluentPut("name", name).fluentPut("isNull", isNull);
        return json;
    }

    private String getFilePath(MultipartFile file) {
        String dirPath = FileUtil.getTmpDirPath();
        try {
            InputStream inputStream = file.getInputStream();
            File fromStream = FileUtil.writeFromStream(inputStream, dirPath + "/" + IdUtil.simpleUUID() + file.getOriginalFilename());
            return fromStream.getAbsolutePath();
        } catch (IOException e) {
            throw new CrmException(SystemCodeEnum.SYSTEM_UPLOAD_FILE_ERROR);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject excelImport(MultipartFile file) {
        List<List<Object>> errList = new ArrayList<>();
        String filePath = getFilePath(file);
        AtomicReference<Integer> num = new AtomicReference<>(0);
        //新增岗位
        List<HrmRecruitPosition> addPositionList = new ArrayList<>();
        //查询所有招聘计划
        List<HrmRecruitPlan> planList = recruitPlanService.list();
        Map<String, HrmRecruitPlan> planMap;
        if (planList != null && !planList.isEmpty()) {
            planMap = planList.stream().collect(Collectors.toMap(item -> Optional.ofNullable(item.getPlanName()).orElse("") + Optional.ofNullable(item.getPlanCode()).orElse(""), Function.identity(), (v1, v2) -> v1));
        } else {
            planMap = new HashMap<>();
        }
        // 岗位类别
        List<String> positionTypeList = RecruitPositionConstant.PositionTypeEnum.getAllTypeNameList();
        String positionTypeStr = String.join("/", positionTypeList);
        // 招聘渠道
        List<String> positionChannelList = RecruitPositionConstant.PositionChannelEnum.getAllChannelNameList();
        String positionChannelStr = String.join("/", positionChannelList);

        ExcelUtil.readBySax(filePath, 0, (int sheetIndex, long rowIndex, List<Object> rowList) -> {
            if (rowIndex > 1) {
                num.getAndSet(num.get() + 1);
                if (rowList.size() < 9) {
                    int size = rowList.size();
                    for (int i = 0; i < 9 - size; i++) {
                        rowList.add("");
                    }
                }
                // 验证必填字段
                if (StrUtil.isEmptyIfStr(rowList.get(0).toString().trim())) {
                    rowList.add(0, "计划名称不能为空");
                    errList.add(rowList);
                    return;
                }
                if (StrUtil.isEmptyIfStr(rowList.get(1).toString().trim())) {
                    rowList.add(0, "计划编号不能为空");
                    errList.add(rowList);
                    return;
                }

                if (!planMap.containsKey(rowList.get(0).toString().trim() + rowList.get(1).toString().trim())) {
                    rowList.add(0, "计划不存在");
                    errList.add(rowList);
                    return;
                }

                if (StrUtil.isEmptyIfStr(rowList.get(2).toString().trim())) {
                    rowList.add(0, "招聘岗位不能为空");
                    errList.add(rowList);
                    return;
                }

                if (StrUtil.isEmptyIfStr(rowList.get(4).toString().trim())) {
                    rowList.add(0, "招聘数量不能为空");
                    errList.add(rowList);
                    return;
                }

                // 验证招聘数量
                Integer positionNum;
                try {
                    positionNum = Integer.parseInt(rowList.get(4).toString().trim());
                    if (positionNum <= 0) {
                        rowList.add(0, "招聘数量必须大于0");
                        errList.add(rowList);
                        return;
                    }
                } catch (NumberFormatException e) {
                    rowList.add(0, "招聘数量格式错误");
                    errList.add(rowList);
                    return;
                }

                // 验证岗位类别
                String positionType = null;
                if (!StrUtil.isEmptyIfStr(rowList.get(6).toString().trim())) {
                    try {
                        positionType = rowList.get(6).toString().trim();
                        if (!positionTypeList.contains(positionType)) {
                            rowList.add(0, "岗位类别必须为[" + positionTypeStr + "]");
                            errList.add(rowList);
                            return;
                        }
                    } catch (NumberFormatException e) {
                        rowList.add(0, "岗位类别格式错误");
                        errList.add(rowList);
                        return;
                    }
                }

                // 验证招聘渠道
                String positionChannel = null;
                if (!StrUtil.isEmptyIfStr(rowList.get(7).toString().trim())) {
                    try {
                        positionChannel = rowList.get(7).toString().trim();
                        if (!positionChannelList.contains(positionChannel)) {
                            rowList.add(0, "招聘渠道必须为[" + positionChannelStr + "]");
                            errList.add(rowList);
                            return;
                        }
                    } catch (NumberFormatException e) {
                        rowList.add(0, "招聘渠道格式错误");
                        errList.add(rowList);
                        return;
                    }
                }
                // 招聘计划
                HrmRecruitPlan recruitPlan = planMap.get(rowList.get(0).toString().trim() + rowList.get(1).toString().trim());

                HrmRecruitPosition position = new HrmRecruitPosition();
                position.setPositionCode(generatePositionCode(recruitPlan.getPlanCode()));
                position.setPlanId(recruitPlan.getPlanId());
                position.setPositionName(rowList.get(2).toString().trim());
                position.setPositionReason(!StrUtil.isEmptyIfStr(rowList.get(3).toString().trim())
                        ? rowList.get(3).toString().trim() : null);
                position.setPositionNum(positionNum);
                position.setPositionCondition(!StrUtil.isEmptyIfStr(rowList.get(5).toString().trim())
                        ? rowList.get(5).toString().trim() : null);
                position.setPositionType(RecruitPositionConstant.PositionTypeEnum.getTypeByName(positionType));
                position.setPositionChannel(RecruitPositionConstant.PositionChannelEnum.getChannelByName(positionChannel));
                position.setPositionUnit(!StrUtil.isEmptyIfStr(rowList.get(8).toString().trim())
                        ? rowList.get(8).toString().trim() : null);
                position.setCreateTime(LocalDateTime.now());
                addPositionList.add(position);
            } else {
                if (rowIndex == 1) {
                    rowList.add(0, "错误信息");
                }
                errList.add(Convert.toInt(rowIndex), rowList);
            }
        });

        if (!addPositionList.isEmpty()) {
            this.saveBatch(addPositionList);
        }
        FileUtil.del(filePath);
        JSONObject result = new JSONObject().fluentPut("totalSize", num.get()).fluentPut("errSize", 0);
        int listSize = 2;
        if (errList.size() > listSize) {
            File errFile = FileUtil.file("excelData/" + IdUtil.simpleUUID() + ".xlsx");
            BigExcelWriter writer = ExcelUtil.getBigWriter(errFile);
            // 取消数据的黑色边框以及数据左对齐
            CellStyle cellStyle = writer.getCellStyle();
            cellStyle.setFillBackgroundColor(IndexedColors.BLACK.getIndex());
            cellStyle.setBorderTop(BorderStyle.NONE);
            cellStyle.setBorderBottom(BorderStyle.NONE);
            cellStyle.setBorderLeft(BorderStyle.NONE);
            cellStyle.setBorderRight(BorderStyle.NONE);
            cellStyle.setAlignment(HorizontalAlignment.LEFT);
            Font defaultFont = writer.createFont();
            defaultFont.setFontHeightInPoints((short) 11);
            cellStyle.setFont(defaultFont);
            // 取消数字格式的数据的黑色边框以及数据左对齐
            CellStyle cellStyleForNumber = writer.getStyleSet().getCellStyleForNumber();
            cellStyleForNumber.setBorderTop(BorderStyle.NONE);
            cellStyleForNumber.setBorderBottom(BorderStyle.NONE);
            cellStyleForNumber.setBorderLeft(BorderStyle.NONE);
            cellStyleForNumber.setBorderRight(BorderStyle.NONE);
            cellStyleForNumber.setAlignment(HorizontalAlignment.LEFT);
            cellStyleForNumber.setFillBackgroundColor(IndexedColors.BLACK.getIndex());
            cellStyleForNumber.setFont(defaultFont);

            CellStyle textStyle = writer.getWorkbook().createCellStyle();
            DataFormat format = writer.getWorkbook().createDataFormat();
            textStyle.setDataFormat(format.getFormat("@"));

            writer.merge(errList.get(1).size() + 1, errList.get(0).get(0).toString().trim(), true);
            writer.getHeadCellStyle().setAlignment(HorizontalAlignment.LEFT);
            writer.getHeadCellStyle().setWrapText(true);
            Font headFont = writer.createFont();
            headFont.setFontHeightInPoints((short) 11);
            writer.getHeadCellStyle().setFont(headFont);
            writer.getHeadCellStyle().setFillPattern(FillPatternType.NO_FILL);
            writer.getOrCreateRow(0).setHeightInPoints(120);
            writer.setRowHeight(-1, 20);

            for (int i = 0; i < errList.get(1).size(); i++) {
                writer.getSheet().setDefaultColumnStyle(i, textStyle);
            }
            errList.remove(0);
            writer.write(errList);
            writer.close();
            //将错误信息的excel保存七天 604800 七天的秒数
            MultipartFile multipartFile = MultipartFileUtil.getMultipartFile(errFile);
            UploadEntity uploadEntity = adminFileService.uploadTempFile(multipartFile, IdUtil.simpleUUID()).getData();

            redis.setex(AdminCacheKey.UPLOAD_EXCEL_MESSAGE_PREFIX + "file:" + uploadEntity.getFileId(), 604800, uploadEntity.getPath());

            result.fluentPut("errSize", errList.size() - 1).fluentPut("token", uploadEntity.getFileId());
        }
        return result;
    }

    @Override
    public UploadEntity uploadTempFile(MultipartFile file, String batchId) {
        Result<UploadEntity> result = adminFileService.uploadTempFile(file, batchId);
        return result.getData();
    }

}
